package com.chookss.home.tuwen;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.TuwenEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import scut.carson_ho.searchview.EditText_Clear;

public class TuwenSearchActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.rlBottom)
    RelativeLayout rlBottom;
    @BindView(R.id.tvBottomSure)
    TextView tvBottomSure;
    private TuwenAdapter tuwenAdapter;
    private List<TuwenEntity> listData = new ArrayList<>();
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private String keyWords = "";
    private int index = -1;//默认不选择

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_tuwen_search);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_title_txt.setText("选择图文");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        tuwenAdapter = new TuwenAdapter(R.layout.item_tuwen, this, listData, 2);
        recyclerView.setAdapter(tuwenAdapter);
        tuwenAdapter.addChildClickViewIds(R.id.rlImgChoice);
        //子控件点击监听
        tuwenAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                switch (view.getId()) {
                    case R.id.rlImgChoice:
                        if (index == position) {
                            index = -1;
                            tuwenAdapter.setChoiceIndex(index);
                            tuwenAdapter.notifyItemChanged(position);
                        } else {
                            tuwenAdapter.notifyItemChanged(index);
                            index = position;
                            tuwenAdapter.setChoiceIndex(index);
                            tuwenAdapter.notifyItemChanged(index);
                        }
                        if(index>-1){
                            tvBottomSure.setBackgroundResource(R.drawable.shape_main_color_12);
                        }else{
                            tvBottomSure.setBackgroundResource(R.drawable.shape_main_color_12_6f);
                        }
                        break;
                }
            }
        });
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(keyWords)) {
                        toSearch();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWords =s.toString();
                if (Utils.isNull(s.toString())) {
                    tvCancel.setText("取消");
                } else {
                    tvCancel.setText("搜索");
                }
            }
        });
        smrRf.autoRefresh();
    }

    private void toSearch() {
        Utils.hideInputKeyboard(TuwenSearchActivity.this, etSearch);
        index=-1;
        tuwenAdapter.setChoiceIndex(index);
        llNone.setVisibility(View.GONE);
        smrRf.setVisibility(View.VISIBLE);
        smrRf.autoRefresh();
        tvBottomSure.setBackgroundResource(R.drawable.shape_main_color_12_6f);
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        if (!Utils.isNull(keyWords)) {
            map.put("title", keyWords);
        }
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<TuwenEntity>>>() {
        }.getType(), null, Urls.getTuwenListAll, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<TuwenEntity>>() {
            @Override
            public void onSuccess(List<TuwenEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    listData.clear();
                    tuwenAdapter.notifyDataSetChanged();
                }
                if (smrRf == null || llNone == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    listData.addAll(data);
                    tuwenAdapter.notifyDataSetChanged();
                    smrRf.setVisibility(View.VISIBLE);
                    rlBottom.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (listData.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        rlBottom.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void uploadTuwen() {
        //发至新闻
        Map<String, Object> map = new HashMap<>();
        map.put("quoteCode", listData.get(index).getMainCode());
        map.put("quoteFlag", "1");
        map.put("shareFlag", listData.get(index).getShareFlag());
        MyHttpRequest.postRequestJson(Urls.addNews, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshNews"));
                        MyToast.show("发至新闻成功");
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("发至新闻失败，请稍后重试");
                }
            }
        });
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.tvCancel, R.id.tvBottomSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
            case R.id.tvCancel:
                if (tvCancel.getText().toString().equals("取消")) {
                    finish();
                } else {
                    toSearch();
                }
                break;
            case R.id.tvBottomSure:
                if (index < 0) {
                    MyToast.show("请选择要发至新闻的图文");
                    return;
                }
                uploadTuwen();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
    }
}
